<template>
<div>
  <!--角色列表导航-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>

  <!--卡片视图-->
  <el-card>
    <!--添加角色入口-->
    <el-button type="primary" @click="showAddDialog">添加角色</el-button>
    <!--角色列表-->
    <el-table border stripe :data="rolesList">
      <el-table-column type="expand">
        <template #default="scope">
<!--          一级权限-->
          <el-row v-for="(item1,index1) in scope.row.children" :key="item1.id" :class="[index1===0?'':'bdtop' ,'vcenter']">
            <el-col :span="5">
              <el-tag closable @close="deleteRight(scope.row,item1.id)">{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <el-col :span="19">
<!--              二级权限-->
              <el-row v-for="(item2,index2) in item1.children" :key="item2.id" :class="[index2===item1.children.length-1?'':'bdbottom','vcenter',]">
                <el-col :span="6">
                  <el-tag closable @close="deleteRight(scope.row,item2.id)">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
<!--                  三级权限-->
                      <el-tag closable type="warning" v-for="item3 in item2.children" :key="item3.id" @close="deleteRight(scope.row,item3.id)">{{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作" width="180px">
        <template #default="scope">
          <el-button size="mini" class="el-icon-edit" type="primary" @click="showEditDialog(scope.row.id)"></el-button>
          <el-button size="mini" class="el-icon-delete" type="danger" @click="deleteRole(scope.row.id)"></el-button>
          <el-tooltip effect="dark" content="分配权限" placement="top-start" :enterable="false">
            <el-button size="mini" class="el-icon-setting" type="warning" @click="showSetRightsDialog(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!--添加角色对话框-->
  <el-dialog
    title="添加角色"
    :visible.sync="addDialogVisible"
    width="50%"
    @close="addDialogClosed"
  >
    <el-form label-width="80px" :model="addForm" :rules="addFormRules" ref="addFormRef">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="addForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="addForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRole">确 定</el-button>
  </span>
    </template>
  </el-dialog>

  <!--编辑角色对话框-->
  <el-dialog
    title="编辑角色"
    :visible.sync="editDialogVisible"
    width="50%"
  >
    <el-form label-width="80px" :model="editForm" :rules="editFormRules" ref="editFormRef">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="editForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="editForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editRole">确 定</el-button>
  </span>
    </template>
  </el-dialog>

  <!--权限树状图对话框-->
  <el-dialog
    title="分配权限"
    :visible.sync="setRightsDialogVisible"
    width="50%"
    @close="setRightsDialogClosed">
    <el-tree
      :data="rightsList"
      show-checkbox
      node-key="id"
      default-expand-all
      :default-checked-keys="selectKeys"
      :props="treeProps"
      ref="treeRef">
    </el-tree>
    <template #footer>
        <span class="dialog-footer">
    <el-button @click="setRightsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRights">确 定</el-button>
  </span>
    </template>
  </el-dialog>
</div>
</template>

<script>
export default {
  name: 'roles',
  data () {
    return {
      rolesList: [],
      addDialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName:
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          },
        roleDesc: {
          message: '请输入角色描述',
          trigger: 'blur'
        }
      },
      setRightsDialogVisible: false,
      editForm: {
        roleName: '',
        roleDesc: '',
        roleId: ''
      },
      editFormRules: {
        roleName:
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          },
        roleDesc: {
          message: '请输入角色描述',
          trigger: 'blur'
        }
      },
      editDialogVisible: false,
      rightsList: [],
      selectKeys: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.$message.success('获取角色列表成功')
      this.rolesList = res.data
    },

    // 显示添加角色对话框
    showAddDialog () {
      this.addDialogVisible = true
    },

    // 关闭后重置添加角色对话框
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },

    // 提交添加角色刷新数据
    async addRole () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整的角色信息')
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.getRolesList()
        this.addDialogVisible = false
      })
    },
    // 删除角色权限
    async deleteRight (roleId, rightId) {
      const result = await this.$confirm('此操作将永久删除该用户权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete(`roles/${roleId.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      // 不使用刷新全部数据,不让列表收起,方便查看改动
      roleId.children = res.data
    },

    // 显示分配角色对话框
    async showSetRightsDialog (role) {
      // 记录当前所点击用户ID
      this.roleId = role.id
      // 记录获取的id
      this.getLeafKey(role, this.selectKeys)
      // 获取权限树
      this.setRightsDialogVisible = true
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限树失败')
      this.rightsList = res.data
    },

    // 获取树所有节点ID
    getLeafKey (node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => this.getLeafKey(item, arr))
    },

    // 关闭对话框重置获取到的权限列表
    setRightsDialogClosed () {
      this.selectKeys = []
    },

    // 设置角色权限
    async setRights () {
      console.log(111)
      // 获取所有全选半选节点的ID
      console.log(this.$refs.treeRef.getCheckedKeys())
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const id = keys.join(',')
      console.log(id)
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: id })
      if (res.meta.status !== 200) return this.$message.error('设置权限失败')
      this.$message.success('设置权限成功')
      this.getRolesList()
      this.setRightsDialogVisible = false
    },

    // 显示编辑角色对话框
    async showEditDialog (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取角色信息失败')
      this.$message.success('获取用户信息成功')
      this.editForm = res.data
    },

    // 提交编辑角色信息
    async editRole () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整的角色信息')
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, this.editForm)
        if (res.meta.status !== 200) return this.$message.error('编辑角色信息失败')
        this.$message.success('编辑用户信息成功')
        this.getRolesList()
        this.editDialogVisible = false
      })
    },

    // 删除角色信息
    async deleteRole (id) {
      const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败')
      this.$message.success('删除角色成功')
      this.getRolesList()
    }
  }
}
</script>

<style scoped>
  .el-tag{
    margin: 7px;
  }
  .bdtop{
  border-top: #eee solid 1px;
}
  .bdbottom{
  border-bottom: #eee solid 1px;
}
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
